<script>
import CommonHeader from "@/components/video/CommonHeader.vue";
import Player, { Danmu } from "xgplayer";
import "xgplayer/dist/index.min.css";
import "xgplayer/es/plugins/danmu/index.css";
import { Events } from "xgplayer";
import VideoAPI from "@/api/qiqq/video.js";
import axios from "axios";
import danmuAPI from "@/api/video/danmuAPI.ts";
// import { useRoute } from "vue-router";
// const route = useRoute();
import dianzanImage1 from "@/assets/icons/dianzan1.png";
import dianzanImage2 from "@/assets/icons/dianzan2.png";
import toubi1 from "@/assets/icons/toubi1.png";
import toubi2 from "@/assets/icons/toubi2.png";
import shoucang1 from "@/assets/icons/shoucang1.png";
import shoucang2 from "@/assets/icons/shoucang2.png";
import { useUserStore } from "@/store/index.ts";

//连接WebSocket，用于统计在线观看人数
/*import Stomp from "stompjs";
import SockJS from "sockjs-client/dist/sockjs.min.js";
import { TOKEN_KEY } from "@/enums/CacheEnum.js";*/
import VideoComment from "@/views/video/comment/VideoComment.vue";
import FollowAPI from "@/api/follow.ts";

export default {
  name: "NewVideoDetail",
  components: { VideoComment, CommonHeader },
  data() {
    return {
      videoDetail: {
        title: "title",
        createTime: "",
        url: "",
      },
      viewCount: "",
      danmuCount: 999,
      videoUpInfo: {},
      player: null,
      onWatching: 20,
      danmuText: "",
      liked: false,
      likeCount: 1001,
      hasCoin: false,
      coinCount: 50,
      collected: false,
      collectCount: 39,
      followed: false,
      showLoginDialog: false,
      defaultDanmuConfig: {
        duration: 5000, //弹幕持续显示时间，单位是毫秒（最低为5000毫秒）
        style: {
          color: "#ffffff",
          padding: "5px 11px",
        },
      },
      ws: null,
      activeNames: ["1"],
      tableData: [],
      danmus: [],
      DianZanImage1: dianzanImage1,
      DianZanImage2: dianzanImage2,
      TouBi1: toubi1,
      TouBi2: toubi2,
      ShouCang1: shoucang1,
      ShouCang2: shoucang2,
      videoUrl: "",
    };
  },

  computed: {
    likeIcon() {
      return this.liked ? this.DianZanImage2 : this.DianZanImage1;
    },

    coinIcon() {
      return this.hasCoin ? this.TouBi2 : this.TouBi1;
    },

    collectIcon() {
      return this.collected ? this.ShouCang2 : this.ShouCang1;
    },
  },
  mounted() {
    this.getVideoDetail();
    this.initPlayer();
    this.initWebsocket();
  },
  methods: {
    //初始化WebSocket，进行连接
    initWebsocket() {
      const url =
        "ws://localhost:8989/imserver/" + localStorage.getItem("token");
      console.log(url);
      this.ws = new WebSocket(url);
      this.ws.onmessage = (event) => {
        const msgObj = JSON.parse(event.data);
        console.log("接收到后端的消息：", msgObj);
        // 如果消息类型是弹幕，则调用播放器发送弹幕
        if (msgObj.txt) {
          console.log("接收到弹幕：", msgObj);
          this.player.danmu.sendComment(msgObj);
        }
        //在线人数通知消息处理
        if (msgObj.onlineCount) {
          this.onWatching = msgObj.onlineCount;
        }
      };
    },

    /**'
     * 初始化player播放器
     * @returns {Promise<void>}
     */
    initPlayer() {
      const vid = this.$route.query.vid;
      VideoAPI.getVideoDetail(vid).then((response) => {
        this.videoUrl = response.videoUrl;
        console.log(this.videoUrl);
        const danmuList = this.getDanmus();
        if (danmuList && danmuList.length > 0) {
          danmuList.forEach((item) => {
            const content = JSON.parse(item.content);
            content.id = item.id;
            this.danmus.push(content);
          });
        }
        this.player = new Player({
          id: "bili-player",
          url: this.videoUrl,
          width: "800px",
          height: "450px",
          plugins: [Danmu],
          danmu: {
            comments: this.danmus,
          },
        });
        console.log(this.videoUrl);
        console.log(this.player.url);
        this.player.danmu.setFontSize("20", "24");
        this.player.on(Events.ENDED, async () => {
          let params = {
            videoId: this.$route.query.videoId,
          };
          await videoApi.addVideoViews(params);
          this.viewCount++;
        });
      });
    },

    /**
     * 获取视频信息、UP主信息、当前用户信息
     */
    getVideoDetail() {
      // const videoId = this.$route.query.videoId;
      //暂定vid为1
      const vid = this.$route.query.vid;
      const UpUid = this.$route.query.uid;
      console.log(UpUid);
      //获得视频详情
      VideoAPI.getVideoDetail(vid).then((response) => {
        this.videoDetail.title = response.title;
        this.videoDetail.createTime = response.uploadDate;
        this.videoDetail.url = response.videoUrl;
      });
      //获得视频Status详情
      VideoAPI.getVideoStatus(vid).then((videoStatusRes) => {
        this.viewCount = videoStatusRes.play;
        this.danmuCount = videoStatusRes.danmu;
        this.likeCount = videoStatusRes.good;
        this.coinCount = videoStatusRes.coin;
        this.collectCount = videoStatusRes.collect;
      });
      //获得视频UP主详情
      VideoAPI.getUserInfo(UpUid).then((userInfoRes) => {
        this.videoUpInfo.avatar = userInfoRes.avatar;
        this.videoUpInfo.nick = userInfoRes.nickname;
        this.videoUpInfo.userId = userInfoRes.id;
      });
      //获得当前用户对视频的userVideo详情
      const userStore = useUserStore();
      const uidCon = userStore.user.userId;
      VideoAPI.getUserVideoInfo({
        uid: uidCon,
        vid: vid,
      }).then((response) => {
        this.liked = response.love;
        this.hasCoin = response.coin;
        this.collected = response.collect;
      });
      //获取当前用户对视频Up的关注情况
      const getPageParams = {
        pageSize: 10,
        pageNo: 1,
      };
      FollowAPI.getPage(getPageParams).then((response) => {
        this.followed = response.list == null ? false : true;
      });
    },

    /**
     * 获得弹幕
     * @returns {Promise<void>}
     */
    getDanmus() {
      //const videoId = this.$route.query.videoId;
      const videoId = 1;
      danmuAPI.findDanmu(videoId).then((response) => {
        let { data: danmuList } = response;
        this.danmuCount = danmuList.length === 0 ? 0 : danmuList.length;
        danmuList.forEach((danmu) => {
          let data = {
            danmuTime: "",
            txt: "",
            createTime: "",
          };
          data.createTime = danmu.createTime;
          const { content: content } = danmu;
          data.txt = JSON.parse(content).txt;
          data.danmuTime = this.millisecondsToMinutesAndSeconds(
            danmu.timePoint
          );
          this.tableData.push(data);
        });
        return danmuList;
      });
    },

    /**
     * 发送弹幕
     */
    sendDanmu() {
      if (!this.isUserLoggedIn) {
        this.showLoginDialog = true;
        return;
      }
      if (this.danmuText) {
        const danmuText = this.danmuText;
        const danmuTime = Math.floor(this.player.currentTime * 1000);
        let danmuMessage = {
          start: danmuTime,
          txt: danmuText,
          duration: this.defaultDanmuConfig.duration,
          style: this.defaultDanmuConfig.style,
        };
        //发送弹幕到后端进行保存
        let params = {};
        params.content = danmuMessage;
        params.videoId = this.$route.query.videoId;
        params.danmuTime = danmuTime;
        this.ws.send(JSON.stringify(params));
        //在前端播放器发送弹幕
        this.danmuText = "";
        danmuMessage.id = 1;
        this.player.danmu.sendComment(danmuMessage);
      }
    },

    /**
     * 点赞、投币、收藏
     */
    addOrDeleteVideoLike() {
      const vid = 1;
      const userStore = useUserStore();
      const uid = userStore.user.userId;
      VideoAPI.love({ uid: uid, vid: vid }).then((response) => {
        console.log(response);
        if (this.liked) {
          this.likeCount--;
        } else {
          this.likeCount++;
        }
        this.liked = !this.liked;
        console.log(this.likeCount);
        console.log(this.liked);
      });
    },

    /**
     * 关注Up主
     */
    addUserFollowings(upId) {
      const userStore = useUserStore();
      const uidCon = userStore.user.userId;
      const params = {
        userId: uidCon,
        followId: upId,
      };
      FollowAPI.followUser(params);
    },
  },
};
</script>

<template>
  <CommonHeader />
  <div class="video-detail-container">
    <div class="left-container">
      <div class="video-info-container">
        <div class="video-info-title">
          {{ videoDetail.title }}
        </div>
        <div class="video-info-count">
          <span>
            <img src="./icon/viewCount.png" alt="" />
            {{ viewCount }}
          </span>
          <span>
            <img src="./icon/danmuCount.png" alt="" />
            {{ danmuCount }}
          </span>
          <span>
            {{ videoDetail.createTime }}
          </span>
          <span>
            <img src="./icon/jinzhi.png" alt="" />
            未经作者授权，禁止转载
          </span>
        </div>
      </div>

      <!--        播放器页面站位DOM-->
      <div id="bili-player"></div>

      <!--数据统计和弹幕操作-->
      <div class="danmu-bar">
        <!--数据统计-->
        <div class="danmu-bar-video-info">
          {{ onWatching }}人正在看，已装填{{ danmuCount }}条弹幕
        </div>
        <!--弹幕操作-->
        <div class="danmu-bar-operation">
          <div class="danmu-bar-sender">
            <input
              class="danmu-bar-sender-input"
              v-model="danmuText"
              placeholder="发个友善的内容见证当下"
              autocomplete="off"
              @keyup.enter="sendDanmu"
            />
            <el-button type="primary" @click="sendDanmu">发送</el-button>
          </div>
        </div>
      </div>

      <!--点赞、投币、收藏-->
      <div class="video-tools-bar">
        <div class="video-tool-bar-left">
          <div class="like-coin-collect" @click="toggleLike">
            <img :src="likeIcon" @click="addOrDeleteVideoLike" alt="" />
            <div>{{ likeCount }}</div>
          </div>
          <div class="like-coin-collect" @click="addVideoCoins">
            <img :src="coinIcon" @click="addVideoCoins" alt="" />
            <div>{{ coinCount }}</div>
          </div>
          <div class="like-coin-collect" @click="toggleCollect">
            <img
              :src="collectIcon"
              @click="addOrDeleteVideoCollection"
              alt=""
            />
            <div>{{ collectCount }}</div>
          </div>
        </div>
      </div>

      <!--        视频描述和视频标签-->
      <div class="left-container-under-player">
        <!--          视频描述-->
        <div class="video-detail-description">
          {{ videoDetail.description }}
        </div>
        <!--          视频标签-->
        <div class="video-detail-tags">
          <el-tag
            type="info"
            style="margin-right: 20px; font-size: 16px"
            v-for="tag in videoDetail.videoTagList"
            :key="tag.tagId"
          >
            {{ tag.tagName }}
          </el-tag>
        </div>
      </div>
      <VideoComment />
    </div>
    <div class="right-container">
      <!--弹幕列表-->
      <div class="right-container">
        <!--        视频投稿的up主信息-->
        <div class="up-info-container">
          <div class="up-avatar">
            <img :src="videoUpInfo.avatar" alt="" />
          </div>
          <div class="up-info-right">
            <div class="up-info-detail">
              {{ videoUpInfo.nick }}
            </div>
          </div>
          <div class="up-operation">
            <el-button
              type="primary"
              v-if="!followed"
              @click="addUserFollowings(videoUpInfo.userId)"
            >
              关注
            </el-button>
            <el-button type="primary" v-else disabled>已关注</el-button>
            <el-dialog
              title="密码登录"
              v-model:visible="showLoginDialog"
              width="30%"
            />
          </div>
        </div>
        <div class="danmu-box">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="弹幕列表" name="1">
              <el-table :data="tableData" style="width: 100%" height="500px">
                <el-table-column label="时间" prop="danmuTime" width="60" />
                <el-table-column label="弹幕内容" prop="txt" width="260" />
                <el-table-column
                  label="发送时间"
                  prop="createTime"
                  width="180"
                />
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.video-detail-container {
  display: flex;
  justify-content: center;

  .left-container {
    display: flex;
    flex-direction: column;

    .video-info-container {
      display: flex;
      height: 108px;
      flex-direction: column;
      justify-content: center;

      .video-info-title {
        font-size: 24px;
        margin-bottom: 5px;
      }
      .video-info-count {
        font-size: 13px;
        align-items: center;
        color: gray;
        display: flex;
        span {
          display: flex;
          align-items: center;
          margin-right: 20px;
          img {
            height: 25px;
            width: 25px;
            border-radius: 2px;
            margin-right: 5px;
          }
        }
      }
    }

    .danmu-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border: 1px solid #d5d2d2;
      border-radius: 2px;

      .danmu-bar-video-info {
        width: 100%;
      }

      .danmu-bar-operation {
        display: flex;
        height: 40px;
        width: 100%;
        border-radius: 8px;
        background: #f4f4f4;

        .danmu-bar-sender {
          display: flex;
          width: 100%;
          align-items: center;
          border: none;
          border-radius: 8px 0 0 8px;
          height: 100%;

          .danmu-bar-sender-input {
            outline: none;
            background: none;
            border: 0;
            color: #212121;
            height: 28px;
            line-height: 28px;
            min-width: 100px;
            padding: 0 5px;
            width: 100%;
          }
        }
      }
    }

    .video-tools-bar {
      margin-top: 10px;
      display: flex;
      align-items: center;
      //justify-content: center;
      border-bottom: 1px solid #d5d2d2;
    }

    .video-tools-bar-left {
      width: auto;
      display: flex;
      align-items: center;
    }
    .like-coin-collect {
      display: flex;
      align-items: center;
      margin-right: 20px;
      cursor: pointer;
      flex: 0 1 auto;
      float: left;
    }
    .like-coin-collect img {
      height: 30px;
      width: 30px;
      margin-right: 10px;
    }
    .like-coin-collect div {
      font-size: 15px;
    }

    .left-container-under-player {
      .video-detail-description {
        max-width: 800px;
        margin: 18px 0;
      }
    }
  }

  .right-container {
    margin-left: 30px;
    display: flex;
    flex-direction: column;

    .up-info-container {
      display: flex;
      align-items: center;
      height: 108px;
      .up-avatar {
        img {
          width: 60px;
          height: 60px;
          border-radius: 5px;
        }
      }
      .up-info-right {
        padding: 20px;
        .up-info-detail {
          color: #fb7299;
        }
      }
    }

    .danmu-box {
      width: 500px;
    }
  }
}
</style>
